package com.baiku.sanhos.controller;

import com.baiku.sanhos.mapper.UserMapper;
import com.baiku.sanhos.pojo.dto.*;
import com.baiku.sanhos.pojo.entity.Booking;
import com.baiku.sanhos.pojo.entity.Doctor;
import com.baiku.sanhos.pojo.entity.User;
import com.baiku.sanhos.pojo.vo.DoctorIndexVo;
import com.baiku.sanhos.pojo.vo.UserIndexVo;
import com.baiku.sanhos.pojo.vo.UserMonthVo;
import com.baiku.sanhos.pojo.vo.UserVo;
import com.baiku.sanhos.response.ResultVO;
import com.baiku.sanhos.response.StatusCode;
import com.baiku.sanhos.utils.security.CustomUserDetails;
import io.swagger.annotations.Api;
//import javafx.scene.input.DataFormat;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
@Slf4j
@RestController
@RequestMapping("/pa/users")
@Api(tags = "用户管理")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @PostMapping( "/deleteByIds")
    @PreAuthorize("hasAuthority('DDD') or hasAuthority('AAA')")
    public ResultVO deleteByIds(@RequestBody List<Integer> ids){
        userMapper.deleteByIds(ids);
        return ResultVO.ok();
    }

    /**
     * 查询全部数据，并且分页
     * @param page
     * @param pageSize
     * @param username
     * @param nickname
     * @return
     */
    @GetMapping("/selectAll")
    @PreAuthorize("hasAuthority('DDD') or hasAuthority('AAA')")
    public ResultVO selectAll(@RequestParam("page") int page,
                              @RequestParam("pageSize") int pageSize,
                              @RequestParam("username") String username,
                              @RequestParam("status") String statu,
                              @RequestParam("nickname") String nickname){
        System.out.println("进来了");
        Map<String, Object> map = new HashMap<>();
        Integer status=null;
        if(statu!=""){
             status = Integer.valueOf(statu);
        }
        int total = userMapper.getTotalUsers(username,status,nickname);//总条数
        int totalPages = (int)Math.ceil((double)total/pageSize);//计算总页数
        List<UserIndexVo> users;
        if(totalPages==0){
            users = new ArrayList<>();
        }else {
            int offset = (page - 1) * pageSize;
            users = userMapper.selectAll(pageSize,offset,username,status,nickname);
        }
        map.put("users", users);
        map.put("total", total);
        return ResultVO.ok(map);
    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    @DeleteMapping("/deleteById/{id}")
    @PreAuthorize("hasAuthority('DDD') or hasAuthority('AAA')")
    public ResultVO deleteById(@PathVariable Integer id){
        userMapper.deleteById(id);
        return ResultVO.ok();
    }

    /**
     * 根据id修改用户帐号的使用状态
     * @param id
     * @return
     */
    @GetMapping("/changStatus/{id}")
    @PreAuthorize("hasAuthority('AAA')")
    public ResultVO updateById(@PathVariable Integer id){
        User user = userMapper.selectById(id);
        int status = user.getStatus()==1 ? 0 : 1;
        user.setStatus(status);
        user.setId(id);
        userMapper.updateById(user);
        User updateUserAfter = userMapper.selectById(id);
        return ResultVO.ok(updateUserAfter);
    }

    /**
     * 根据id充值金额
     * @param id
     * @param amount
     * @return
     */
    @GetMapping("/topUp")
    @PreAuthorize("hasAuthority('DDD') or hasAuthority('AAA')")
    public ResultVO topUp(@RequestParam("id") Integer id,@RequestParam("amount") Double amount){
        User user = userMapper.getSelectById(id);
        Double topUpAmount = user.getAmount()+amount;//充值后的值
        user.setRecharge_time(new Date());
        userMapper.updateUserById(id,topUpAmount,user.getRecharge_time());
        return ResultVO.ok();
    }

    /**
     * 编辑
     * @param userListDTO
     * @return
     */
    @PutMapping("/updateById")
    @PreAuthorize("hasAuthority('DDD') or hasAuthority('AAA')")
    public ResultVO updateById(@RequestBody UserListDTO userListDTO){
        userListDTO.setUpdateTime(new Date());
        userMapper.editUserById(userListDTO);
        return ResultVO.ok();
    }

    /**
     * 月收入
     */
    @GetMapping("/month")
    @PreAuthorize("hasAuthority('DDD') or hasAuthority('AAA')")
    public ResultVO month(){
        System.out.println(new Date());
        Map<String, Double> map = new LinkedHashMap<>();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
        String date = dateFormat.format(new Date());
        String newYear= date.substring(0, 4);//当前年份
        List<UserMonthVo> userList = userMapper.selectMonth();
        // 初始化所有月份的收入为0
        for (int i = 1; i <= 12; i++) {
            String month = String.format("%02d", i);
            String monthStr = month + "月";
            map.put(monthStr, 0.0);
        }

        for (UserMonthVo user : userList) {
            if(user.getRechargeTime()==null || user.getRechargeTime().equals("")){
                user.setRechargeTime(new Date());
            }
            String strDate = dateFormat.format(user.getRechargeTime());//获取数据库的年月份
            if (strDate.substring(0, 4).equals(newYear)) {
                String month = strDate.substring(strDate.length() - 2) + "月";
                Double amount = map.getOrDefault(month, 0.0);
                amount += user.getAmount();
                map.put(month, amount);
            }
        }
        return ResultVO.ok(map);
    }
    @ApiOperation("根据账号获取用户首页默认数据")
    @GetMapping("/getUserInfo/{username}")
    @PreAuthorize("hasAnyAuthority('Details')")
    public ResultVO getUserInfo(@PathVariable String username){
        return ResultVO.ok(userMapper.getUserInfo(username));
    }

    @ApiOperation("根据账号获取用户首页默认数据")
    @PostMapping("/updateUserInfo")
    @PreAuthorize("hasAnyAuthority('Details')")
    public ResultVO updateUserInfo(@RequestBody UserIndexInfoDTO userIndexInfoDTO){
        userMapper.updateUserInfo(userIndexInfoDTO);
        return ResultVO.ok();
    }
}
